package cc.orange.mainView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import cc.orange.R;
import cc.orange.adapter.HomeAdapter;
import cc.orange.base.BaseActivity;
import cc.orange.databinding.ActivityShellLikeBinding;
import cc.orange.entity.ChatListEntity;
import cc.orange.entity.LoginsEntity;
import cc.orange.entity.MsgLoginUI3Entity;
import cc.orange.entity.NoteExtrEntity;
import cc.orange.entity.SuerInfosEntity;
import cc.orange.entity.UpdataUserPostEntity;
import cc.orange.http.ApiService;
import cc.orange.utils.CheckNotifyPermissionUtils;
import cc.orange.utils.RequestPermissions;
import cc.orange.utils.ScreenUtils;
import cc.orange.utils.ZXToastUtil;
import cc.orange.utils.popup.PopupSeMSgView;
import cc.orange.utils.popup.PopupShakeView;
import demo.smart.access.xutlis.util.ZXSharedPrefUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.xcheng.retrofit.Call;
import com.xcheng.retrofit.DefaultCallback;
import com.xcheng.retrofit.HttpError;
import com.xcheng.retrofit.RetrofitFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/*悄悄话*/
public class ShellLikeActivity extends BaseActivity implements View.OnClickListener {
    private HomeAdapter adapter;
    private List<ChatListEntity.Data.DataList> list = new ArrayList<>();
    private ActivityShellLikeBinding binding;
    private SuerInfosEntity entity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_shell_like);
        initView();
        chatList();
        getSuserInfo();
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void getHight(String entity){
        if(entity.equals("home_refres")){
            list.clear();
            chatList();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initView() {

        RelativeLayout.LayoutParams pp = new RelativeLayout.
                LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ScreenUtils.getStatusBarHeight(ShellLikeActivity.this));
        binding.msglistTitle.setLayoutParams(pp);

        adapter = new HomeAdapter(list);
        binding.homeRecycler.setLayoutManager(new LinearLayoutManager(this));
        binding.homeRecycler.setAdapter(adapter);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(ShellLikeActivity.this, ConversationListActivity.class);
                intent.putExtra("uid", "" + list.get(position).getWomanId());
                intent.putExtra("u_name",
                        ""+(TextUtils.isEmpty(list.get(position).getRemarkName()) ?
                                list.get(position).getName() : list.get(position).getRemarkName()));
                intent.putExtra("u_spare", "" + list.get(position).getSpareStatus());
                intent.putExtra("type_t", "1");
                startActivity(intent);

                list.get(position).setUnreadNum(0);
                adapter.notifyDataSetChanged();
            }
        });

        binding.msginfoBack.setOnClickListener(this);

        binding.msgRel2.setOnClickListener(this);
        binding.shellRetur.setOnClickListener(this);
        binding.shellShellike.setOnClickListener(this);
        binding.shellRecives.setOnClickListener(this);
        binding.msgRel4.setOnClickListener(this);

        initHeadVisb();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.msginfo_back:
                finish();
                break;
            case R.id.msg_rel2://通知
                RequestPermissions.getPermissions_notfi(ShellLikeActivity.this, new RequestPermissions.SuccessInterf() {
                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onSuccess() {
                        entity.getData().getNewsRemind().equals("1");
                        updateNotify();
                    }
                });
                break;
            case R.id.shell_retur://回应
                ZXSharedPrefUtil ss1 = new ZXSharedPrefUtil();
                ss1.putInt("hand_5", 1);
                initHeadVisb();
                if (list.size() <= 0) {
                    ZXToastUtil.showToast("暂时还没人回应你");
                } else {
                    Intent intent = new Intent(ShellLikeActivity.this, ConversationListActivity.class);
                    intent.putExtra("uid", "" + list.get(0).getWomanId());
                    intent.putExtra("u_name",
                            ""+(TextUtils.isEmpty( list.get(0).getRemarkName()) ?
                                    list.get(0).getName() :  list.get(0).getRemarkName()));
                    intent.putExtra("u_spare", "" + list.get(0).getSpareStatus());
                    intent.putExtra("type_t", "1");
                    startActivity(intent);

                    list.get(0).setUnreadNum(0);
                    adapter.notifyDataSetChanged();
                }
                break;
            case R.id.shell_shellike://悄悄话
                ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
                ss.putInt("hand_4", 1);
                PopupShakeView(1);
                break;
            case R.id.shell_recives://收一条
                collect();
                break;
            case R.id.msg_rel4://重要提示
                startActivity(new Intent(ShellLikeActivity.this, ConverNotesFActivity.class));
                break;
        }
    }


    private void chatList() {
        RetrofitFactory.create(ApiService.class)
                .chatList(getTokens(),"1")//消息列表类型(0首页消息,1悄悄话消息)
                .enqueue(new DefaultCallback<ChatListEntity>() {
                    @Override
                    public void onStart(Call<ChatListEntity> call) {
                        showLoading_base(ShellLikeActivity.this);
                    }

                    @Override
                    public void onError(Call<ChatListEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<ChatListEntity> call, ChatListEntity baseEntity) {
                        cancelLoading();
                        if (baseEntity.getCode() == 0) {
                            list.addAll(baseEntity.getData().getDataList());
                            adapter.notifyDataSetChanged();
                        } else {
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }


    private void collect() {

        RetrofitFactory.create(ApiService.class)
                .collect(getTokens())
                .enqueue(new DefaultCallback<ChatListEntity>() {
                    @Override
                    public void onStart(Call<ChatListEntity> call) {
                        showLoading_base(ShellLikeActivity.this);
                    }

                    @Override
                    public void onError(Call<ChatListEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<ChatListEntity> call, ChatListEntity baseEntity) {
                        cancelLoading();
                        if (baseEntity.getCode() == 0) {
                            list.clear();
                            chatList();
                        } else {
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }

    private void holeAdd(String contents) {
        String s = "{\"sendContent\":\"" + contents + "\"}";
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .holeAdd(getTokens(), requestBody1)
                .enqueue(new DefaultCallback<ChatListEntity>() {
                    @Override
                    public void onStart(Call<ChatListEntity> call) {
                        showLoading_base(ShellLikeActivity.this);
                    }

                    @Override
                    public void onError(Call<ChatListEntity> call, HttpError error) {
                        cancelLoading();
                        ZXToastUtil.showToast("出错了，请稍后重试");
                    }

                    @Override
                    public void onSuccess(Call<ChatListEntity> call, ChatListEntity baseEntity) {
                        cancelLoading();
                        if (baseEntity.getCode() == 0) {
                            ZXToastUtil.showToast("已扔进树洞");
                        } else {
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                        initHeadVisb();
                    }
                });
    }


    private void PopupShakeView(int types) {
        PopupShakeView.showPopupwindow(this, binding.homeImg12, new PopupShakeView.PopuStatus() {
            @Override
            public void popupShow() {

            }

            @Override
            public void popupDismissCancle(String se1) {
                holeAdd(se1);
            }
        });
    }

    //首次时  弹提示框
    private void PopupFirstView() {
        PopupSeMSgView.showPopupwindow(this, binding.homeImg12, new PopupSeMSgView.PopuStatus() {
            @Override
            public void popupShow() {

            }

            @Override
            public void popupDismissCancle(String se1) {
                ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
                ss.putInt("hand_6", 1);
                initHeadVisb();
                if(se1.equals("1")){
                    collect();
                }
            }
        });
    }


    private void checkNotf() {
        boolean b1 = CheckNotifyPermissionUtils.checkNotifyPermission(ShellLikeActivity.this);
        if (entity.getData().getNewsRemind().equals("0")) {//是否开启消息提醒(0关闭,1开启)
            binding.msgRel2.setVisibility(View.VISIBLE);
        } else if (entity.getData().getNewsRemind().equals("1") && b1) {//是否开启消息提醒(0关闭,1开启)
            binding.msgRel2.setVisibility(View.GONE);
        } else {
            binding.msgRel2.setVisibility(View.VISIBLE);
        }
    }


    private void updateNotify() {
        UpdataUserPostEntity entitys = new UpdataUserPostEntity();
        entitys.setNewsRemind("1");
        Gson gss = new Gson();
        String s = gss.toJson(entitys);
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .updateUser(getTokens(), requestBody1)
                .enqueue(new DefaultCallback<LoginsEntity>() {
                    @Override
                    public void onStart(Call<LoginsEntity> call) {
                        showLoading_base(ShellLikeActivity.this);
                    }

                    @Override
                    public void onError(Call<LoginsEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<LoginsEntity> call, LoginsEntity baseEntity) {
                        cancelLoading();
                        if (baseEntity.getCode() == 0) {
                            ZXToastUtil.showToast("已开启聊天消息提醒");
                            EventBus.getDefault().post(new String("getsus"));
                        } else {
                        }
                    }
                });
    }



    private void getSuserInfo(){
        RetrofitFactory.create(ApiService.class)
                .getSuserInfo(getTokens())
                .enqueue(new DefaultCallback<SuerInfosEntity>() {
                    @Override
                    public void onStart(Call<SuerInfosEntity> call) {
                        showLoading_base(ShellLikeActivity.this);
                    }

                    @Override
                    public void onError(Call<SuerInfosEntity> call, HttpError error) {
                        cancelLoading();
//                        EventBus.getDefault().post(new MsgLoginUI3Entity(true));
                    }

                    @Override
                    public void onSuccess(Call<SuerInfosEntity> call, SuerInfosEntity baseEntity) {
                        cancelLoading();
                        EventBus.getDefault().postSticky(baseEntity);
                        if(baseEntity.getCode() == 0){
                            entity = baseEntity;
                            checkNotf();
                        }else{
//                            EventBus.getDefault().post(new MsgLoginUI3Entity(true));
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }


    private void initHeadVisb() {
        ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
        boolean isLogin = ss.getBool("isLogin_hr",false);
        if(!isLogin )return;

        int hand_4 = ss.getInt("hand_4", 0);
        if (hand_4 == 0) {
            binding.shellHend1.setVisibility(View.VISIBLE);
            initHandAnim(binding.shellHend1);
            binding.shellHend2.setVisibility(View.GONE);
            return;
        } else {
            binding.shellHend1.clearAnimation();
            binding.shellHend1.setVisibility(View.GONE);
        }

        int hand_6 = ss.getInt("hand_6", 0);
        if (hand_6 == 0 && hand_4 == 1) {
            binding.shellHend2.setVisibility(View.GONE);
            binding.shellHend1.setVisibility(View.GONE);
            PopupFirstView();
            return;
        } else {
            binding.shellHend1.clearAnimation();
            binding.shellHend1.setVisibility(View.GONE);
        }

        int hand_5 = ss.getInt("hand_5", 0);
        if (hand_5 == 0) {
            binding.shellHend2.setVisibility(View.VISIBLE);
            initHandAnim(binding.shellHend2);
            binding.shellHend1.setVisibility(View.GONE);
            return;
        } else {
            binding.shellHend2.clearAnimation();
            binding.shellHend2.setVisibility(View.GONE);
        }
    }


    private void initHandAnim(View view){
        ObjectAnimator scaleX7 = ObjectAnimator.ofFloat(view, "translationY", 0f,20, 0f);
        ObjectAnimator scaleY7 = ObjectAnimator.ofFloat(view, "translationY", 0f,-20, 0f);
        scaleX7.setDuration(1500);
        scaleY7.setDuration(1500);
        scaleX7.start();
        scaleX7.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                scaleY7.start();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        scaleY7.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                scaleX7.start();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }
}